import os
import json
from UserDb import UserDb
from CatalogDb import CatalogDb
from AccountDb import AccountDb
import logging

def convertCatalogList(catalogList):
    result = {
        'label': 'name',
        'identifier': 'key',
        'items':[],
        }

    for catalog in catalogList:
        if (catalog.catalogParent):
             catalogItem = {
                'name':catalog.catalogName, 
                'key':catalog.key().id(), 
                'parent':catalog.catalogParent.key().id(),
                'type':'catalog',
                'children':[]}
        else:
            catalogItem = {
                'name':catalog.catalogName, 
                'key':catalog.key().id(), 
                'type':'root',
                'children':[]}
        result['items'].append(catalogItem)
    
    for catalogItem in result['items']:
        if('parent' in catalogItem):
            i = 0;
            while i<len(result['items']):
                if result['items'][i]['key']==catalogItem['parent']:
                    result['items'][i]['children'].append({'_reference':str(catalogItem['key'])})
                    break
                else:
                    i = i+1
    return result 

def convertAccountList(accountList):
    result = {
            'items':[]
        }
    for account in accountList:
        accountItem = {
            'key': account.key().id(),
            'name': account.accountName,
            'accountId': account.accountId,
            'password': account.accountPassword,
            'url': account.accountUrl,
            'catalogKey': account.accountCatalog.key().id(),
            'catalogName': account.accountCatalog.catalogName,
            'type':'account'
            }
        result['items'].append(accountItem)
    return result  